package com.iwhalecloud.bss.kite.cucc.service.custview.evolve.task;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.ProdInstQryDTO;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.CustViewAttr;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.CustViewBaseVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.CustViewVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.custview.GroupUserInfoVO;
import com.iwhalecloud.bss.kite.cucc.service.custview.userinfo.UserAttrSupplierFactory;
import com.iwhalecloud.bss.kite.cucc.service.custview.userinfo.UserInfoContext;
import com.iwhalecloud.bss.kite.cucc.service.custview.userinfo.UserInfoHelper;
import com.iwhalecloud.bss.kite.cucc.service.custview.userinfo.supplier.AbstractUserAttrSupplier;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.cache.KiteAttrConfigCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.dataservice.entity.KiteAttrConfig;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;

import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.common.logger.api.ZLogger;
import com.ztesoft.common.logger.factory.ZLoggerFactory;

/**
 * @ClassName : UserInfoTask
 * @Description : 集团用户信息
 * @Author : xie.zhengjun
 * @Date : 2021/4/30 18:31
 */
public class UserInfoTask extends AbstractCustViewTask{
    private final ZLogger LOGGER = ZLoggerFactory.getLogger(this.getClass(), KeyConsts.LOG_MODULE);
    @Override
    public CustViewBaseVO call(Object[] args) {
        Map<String, Object> userDetail = (Map<String, Object>) args[0];
        CustViewVO custViewVO = (CustViewVO) args[1];
        String inDepartName = (String) args[2];
        GroupUserInfoVO groupUserInfoVO = new GroupUserInfoVO();
        custViewVO.setGroupUser(groupUserInfoVO);
        List<CustViewAttr> custViewAttrs = new ArrayList<>();
        groupUserInfoVO.setAttrs(custViewAttrs);

        if (KiteMapUtils.isNotEmpty(userDetail)) {
            // 用户信息
            Map<String, Object> userInfo = (Map<String, Object>) userDetail.get("USER_INFO");
            // 合同信息
            List<Map<String, Object>> userContractInfos = (List<Map<String, Object>>) userDetail
                .get("USER_CONTRACT_INFOS");
            // 订单属性
            List<Map<String, Object>> userItemInfos = (List<Map<String, Object>>) userDetail.get("USER_ITEM_INFOS");
            Map<String, Map<String, Object>> userItemInfoMap = null;
            if (KiteListUtils.isNotEmpty(userItemInfos)) {
                userItemInfoMap = userItemInfos.stream().collect(Collectors
                    .toMap(stringObjectMap -> KiteMapUtils.getString(stringObjectMap, "CRM_ATTR_CODE"),
                        stringObjectMap -> stringObjectMap, (a, b) -> b));
            }

            String goodsId = KiteMapUtils.getString(userInfo, "GOODS_ID");
            String custId = KiteMapUtils.getString(userInfo, "CUST_ID");
            String serialNumberVal = KiteMapUtils.getString(userInfo, "SERIAL_NUMBER");
            String provinceCode = KiteMapUtils.getString(userInfo, "PROVINCE_CODE");
            String eparchyCode = KiteMapUtils.getString(userInfo, "EPARCHY_CODE");

            List<KiteAttrConfig> attrConfigs = getAttrConfigs(goodsId);

            UserAttrSupplierFactory userAttrSupplierFactory = SpringUtil.getBean(UserAttrSupplierFactory.class);
            for (KiteAttrConfig kiteAttrConfig : attrConfigs) {
                String attrField = kiteAttrConfig.getAttrField();
                if (KiteStringUtils.isEmpty(attrField)) {
                    continue;
                }
                UserInfoContext userInfoContext = new UserInfoContext(userInfo, userContractInfos, userItemInfoMap,
                    attrField, kiteAttrConfig.getAttrName(), kiteAttrConfig.getSort());
                AbstractUserAttrSupplier userAttrSupplier = null;
                try {
                    userAttrSupplier = userAttrSupplierFactory
                        .getUserAttrSupplier(userInfoContext);
                }
                catch (IllegalAccessException | InstantiationException e) {
                    LOGGER.error(ErrorConsts.SYSTEM_ERROR.getErrorCode(), e, "获取用户属性提供者失败");
                }
                if (Objects.nonNull(userAttrSupplier)) {
                    custViewAttrs.add(userAttrSupplier.get());
                }
            }

            additionalAttr(custViewAttrs, userInfo, goodsId, custId, serialNumberVal, provinceCode, eparchyCode, inDepartName);

            setContract(groupUserInfoVO, custViewAttrs, userInfo, userContractInfos);
        }
        return groupUserInfoVO;
    }

    /**
     * 添加额外属性
     *
     * @param custViewAttrs
     * @param userInfo
     * @param goodsId
     * @param custId
     * @param serialNumberVal
     * @param provinceCode
     * @param eparchyCode
     */
    private void additionalAttr(List<CustViewAttr> custViewAttrs, Map<String, Object> userInfo, String goodsId,
        String custId, String serialNumberVal, String provinceCode, String eparchyCode,
        String inDepartName) {
        // 4 产品名称 GOODS_ID
        String prodNameDesc = Optional.ofNullable(OfferCache.get(goodsId)).map(Offer::getOfferName).orElse(goodsId);
        CustViewAttr prodName = new CustViewAttr("prodName", "产品名称", goodsId, prodNameDesc);

        // 5 集团用户状态
        String userStateCode = Optional.ofNullable(String.valueOf(userInfo.get("SERVICE_STATE_CODE"))).orElse("");
        String userStateCodeDesc = Optional.ofNullable(AttrValueCache.getAttrValue("2020012105", userStateCode))
            .map(AttrValue::getAttrValueName).orElse(userStateCode);
        CustViewAttr state = new CustViewAttr("state", "集团用户状态", userStateCode, userStateCodeDesc);

        // 16 开户时间 OPEN_DATE
        String openDateVal = KiteMapUtils.getString(userInfo, "OPEN_DATE");
        //格式化时间 2021-01-07 14:59:00
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String openDateValDesc = "";
        try {
            Date parse = sdf.parse(openDateVal);
            openDateValDesc = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(parse);
        } catch (ParseException e) {
            LOGGER.error(ErrorConsts.SYSTEM_ERROR.getErrorCode(), "时间转换出错");
        }
        CustViewAttr openDate = new CustViewAttr("openDate", "开户时间", openDateVal,
            KiteStringUtils.isEmpty(openDateValDesc) ? openDateVal : openDateValDesc);

        // 17 注销时间
        ProdInstQryDTO prodInstQryDTO = UserInfoHelper
            .getProdInstQryDTO(custId, serialNumberVal, provinceCode, eparchyCode);
        String cancelDateVal = "";
        if (Objects.nonNull(prodInstQryDTO)) {
            cancelDateVal = prodInstQryDTO.getDistroy_time();
            if (KiteStringUtils.isEmpty(cancelDateVal)) {
                String destroyDateStr = KiteMapUtils.getString(userInfo, "DESTROY_DATE");
                if (KiteStringUtils.isNotEmpty(destroyDateStr)) {
                    try {
                        Date destroyDate = new SimpleDateFormat("yyyyMMddHHmmss").parse(destroyDateStr);
                        cancelDateVal = KiteDateUtils.formatDate(destroyDate, "yyyy-MM-dd HH:mm:ss");
                    } catch (ParseException e) {
                        LOGGER.error(ErrorConsts.SYSTEM_ERROR.getErrorCode(), e, "注销时间失败");
                    }
                }
            }
        }
        CustViewAttr cancelDate = new CustViewAttr("cancelDate", "注销时间", cancelDateVal, cancelDateVal);

        // 18 建档员工 IN_STAFF_ID
        String inStaffId = KiteMapUtils.getString(userInfo, "IN_STAFF_ID");
        String staffName = inStaffId;
        if (Objects.nonNull(prodInstQryDTO)) {
            staffName = prodInstQryDTO.getIn_staff_name();
        }
        CustViewAttr inStaff = new CustViewAttr("inStaff", "建档员工", inStaffId, staffName);

        // 19 建档渠道 IN_DEPART_ID 110SPW400047存在
        String inDepartId = KiteMapUtils.getString(userInfo, "IN_DEPART_ID");

        if (KiteStringUtils.isEmpty(inDepartName)) {
            if (Objects.nonNull(prodInstQryDTO)) {
                inDepartName = prodInstQryDTO.getIn_depart_name();
            }
        }
        if (KiteStringUtils.isEmpty(inDepartName)) {
            inDepartName = inDepartId;
        }
        CustViewAttr inDepart = new CustViewAttr("inDepart", "建档渠道", inDepartId, inDepartName);

        custViewAttrs.add(0, prodName);
        custViewAttrs.add(1, state);
        custViewAttrs.add(openDate);
        custViewAttrs.add(cancelDate);
        custViewAttrs.add(inStaff);
        custViewAttrs.add(inDepart);
    }

    /**
     * 设置合同
     *
     * @param groupUserInfoVO
     * @param custViewAttrs
     * @param userInfo
     * @param userContractInfos
     */
    private void setContract(GroupUserInfoVO groupUserInfoVO, List<CustViewAttr> custViewAttrs,
        Map<String, Object> userInfo, List<Map<String, Object>> userContractInfos) {
        String contractId = "";
        String contractType="";
        if (KiteListUtils.isNotEmpty(userContractInfos)) {
            Map<String, Object> userContractInfo = userContractInfos.get(0);
            contractId = KiteMapUtils.getString(userContractInfo, "CONTRACT_ID");
            contractType = KiteMapUtils.getString(userContractInfo, "DATA_CODE");

        }
        CustViewAttr contract = new CustViewAttr("contract", "合同", contractId, "详情");
        custViewAttrs.add(contract);
        groupUserInfoVO.setContractType(contractType);
        groupUserInfoVO.setContractId(contractId);
        groupUserInfoVO.setCustId(KiteMapUtils.getString(userInfo, "CUST_ID"));
        groupUserInfoVO.setProvinceCode(KiteMapUtils.getString(userInfo, "PROVINCE_CODE"));
    }

    /**
     * 获取该商品订购时用户信息模块上的属性
     *
     * @param goodsId
     * @return
     */
    private List<KiteAttrConfig> getAttrConfigs(String goodsId) {
        List<KiteAttrConfig> attrConfigs = new ArrayList<>();
        if (KiteStringUtils.isEmpty(goodsId)) {
            return attrConfigs;
        }

        String catId = Optional.ofNullable(OfferCache.get(goodsId)).map(Offer::getCateId).orElse("");
        if (KiteStringUtils.isEmpty(goodsId)) {
            return attrConfigs;
        }

        String serviceOfferId = "1";

        List<KiteAttrConfig> allAttrConfigs = KiteAttrConfigCache
            .get(KeyConsts.COMMON_OBJECT_TYPE + "_" + serviceOfferId);
        if (KiteListUtils.isEmpty(allAttrConfigs)) {
            return attrConfigs;
        }

        attrConfigs = allAttrConfigs.stream()
            .filter(kiteAttrConfig -> KiteStringUtils.isEqual(kiteAttrConfig.getModuleId(), "113"))
            .filter(kiteAttrConfig -> KiteStringUtils.isEqual(catId, kiteAttrConfig.getCatagoryId()))
            .collect(Collectors.toList());
        // 不存在该产品分类的则查询-1的
        if (KiteListUtils.isEmpty(attrConfigs)) {
            attrConfigs = allAttrConfigs.stream()
                .filter(kiteAttrConfig -> KiteStringUtils.isEqual(kiteAttrConfig.getModuleId(), "113"))
                .filter(kiteAttrConfig -> KiteStringUtils.isEqual("-1", kiteAttrConfig.getCatagoryId()))
                .collect(Collectors.toList());
        }
        /*attrConfigs = attrConfigs.stream()
            .filter(kiteAttrConfig -> !KiteStringUtils.isEqual(kiteAttrConfig.getIsShow(), "H"))
            .collect(Collectors.toList());*/
        return attrConfigs;
    }
}
